﻿var xColumnDisplay = 4;
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

// this function is fired when the document is in the ready state.
function documentLoad() {

    /* Hide the Advanced Search box */
    $("#advancedNewsSearch").hide();
    var now = new Date();
    var startDate = new Date();
    var endDate = new Date();

    /* Set the default news range */
    startDate.setDate(now.getDate() - 1);
    endDate.setDate(now.getDate());

    /* Add calendars to search dates */
    $("#searchStartDate").datepicker({ onSelect: function (date) { },
        showOn: "both", yearRange: now.getYear() + ':' + now.getYear(), dateFormat: 'MM dd, yy'
    });

    //$("#searchStartDate")[0].innerText = m_names[startDate.getMonth()] + " " + startDate.getDate() + ", " + startDate.getFullYear();
    $("#searchStartDate")[0].value = m_names[startDate.getMonth()] + " " + startDate.getDate() + ", " + startDate.getFullYear();
    $("#searchStartDate").attr('readonly', true);

    //dd-MM-yy
    $("#searchEndDate").datepicker({ onSelect: function(date)
    { }, showOn: "both", yearRange: now.getYear() + ':' + now.getYear(), dateFormat: 'MM dd, yy'
    });
    $("#searchEndDate")[0].value = m_names[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
    $("#searchEndDate").attr('readonly', true);

    /* Attach event handlers to new items. */
    $("#advancedSearchHref").click(function() {
        var searchBox = $("#advancedNewsSearch");
        if (searchBox.is(":hidden")) {
            searchBox.show();
        }
        else {
            searchBox.hide();
        }
    });

    $("#btnHideSearch").click(function() {
        var searchBox = $("#advancedNewsSearch");
        searchBox.hide();
    });

    $("#btnSearch").click(function(args) {

        Search();
        return false;
    });

    $("#newsSearch").keypress(function(args) {
        if (args.keyCode == 13) {
            Search();
            return false;
        }
    });

    $("#btnClear").click(function(args) {
        $("#txtSearch")[0].value = "";
        Search();
        return false;
    });

    $("#topHeadlines").click(function() {
        var $this = $(this);
        /* Set the default news range */
        var now = new Date();
        var startDate = new Date();
        var endDate = new Date();
        startDate.setDate(now.getDate() - 1);
        endDate.setDate(now.getDate());
        $("#searchStartDate")[0].innerText = m_names[startDate.getMonth()] + " " + startDate.getDate() + ", " + startDate.getFullYear();
        $("#searchEndDate")[0].innerText = m_names[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
        SelectAllSources();
        SelectSort("F");

        $this.addClass("newsRangeSelected");
        $("#topIn24Hr").addClass("newsRange");
        $("#topWeek").addClass("newsRange");
        $this.removeClass("newsRange");
        $("#topIn24Hr").removeClass("newsRangeSelected");
        $("#topWeek").removeClass("newsRangeSelected");
        Search();
    });

    $("#topIn24Hr").click(function() {
        var $this = $(this);

        /* Set the default news range */
        var now = new Date();
        var startDate = new Date();
        var endDate = new Date();
        startDate.setDate(now.getDate() - 1);
        endDate.setDate(now.getDate());
        $("#searchStartDate")[0].innerText = m_names[startDate.getMonth()] + " " + startDate.getDate() + ", " + startDate.getFullYear();
        $("#searchEndDate")[0].innerText = m_names[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
        SelectAllSources();
        SelectSort("P");

        $this.addClass("newsRangeSelected");
        $("#topHeadlines").addClass("newsRange");
        $("#topWeek").addClass("newsRange");
        $this.removeClass("newsRange");
        $("#topHeadlines").removeClass("newsRangeSelected");
        $("#topWeek").removeClass("newsRangeSelected");
        Search();
    });

    $("#topWeek").click(function() {
        var $this = $(this);
        /* Set the default news range */
        var now = new Date();
        var startDate = new Date();
        var endDate = new Date();
        startDate.setDate(now.getDate() - 7);
        endDate.setDate(now.getDate());
        $("#searchStartDate")[0].innerText = m_names[startDate.getMonth()] + " " + startDate.getDate() + ", " + startDate.getFullYear();
        $("#searchEndDate")[0].innerText = m_names[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
        SelectAllSources();
        SelectSort("P");

        $this.addClass("newsRangeSelected");
        $("#topHeadlines").addClass("newsRange");
        $("#topIn24Hr").addClass("newsRange");
        $this.removeClass("newsRange");
        $("#topHeadlines").removeClass("newsRangeSelected");
        $("#topIn24Hr").removeClass("newsRangeSelected");
        Search();
    });

    LoadNewsSections();
    LoadSortByList();
    /* Call search in the longest running method since it will not be ready if called synchronously */
    LoadNewsSourcesInSelectList();

    $("#newsSearch").focus();
}

function SelectAllSources() {
    /* Select all options in a select box */
    var sourceList = $('#searchNewsSourceSelection')[0];
    if (sourceList != null) {
        for (var i = 0; i < sourceList.options.length; i++) {
            sourceList.options[i].selected = true;
        }
    }
}

function stripHTML(arguments) {
    var re = /(<([^>]+)>)/gi;
    return arguments.replace(re, "")
}

function SelectSort(sortByField) {
    var sortBy = $("#searchSortBy")[0];
    switch (sortByField) {
        case "P":
            sortBy.options[0].selected = true;
            break
        default:
            sortBy.options[1].selected = true;
            break;
    }
}

function Search() {
    var sourceList = $('#searchNewsSourceSelection')[0];
    var source;
    var imgLoading;
    var divNews;
    var search;
    var sourcesList;
    var newsTable;

    newsTable = $("#newsWallTable");
    imgLoading = "#img" + source;
    imgLoading = $("#imgLoading");
    /* Validations */
    //searchStartDate
    search = "request=" + JSON.stringify(BuildSearchString(source));
    imgLoading[0].style.display = "block";
    imgLoading[0].visible = true;
    ClearErrorMessage();
    CallWebService(newsSearchUrl,
        search,
        function(result) {
            var sourceList = $('#searchNewsSourceSelection')[0];
            var source;
            var imgLoading;
            var divNews;
            var search;
            var sourcesList;
            var newsTable;

            newsTable = $("#newsWallTable");
            imgLoading = "#img" + source;
            imgLoading = $("#imgLoading");

            if (imgLoading[0] != null) {
                imgLoading[0].visible = false;
                imgLoading[0].style.display = "none";
            }
            var response = JSON.parse(result.d);
            if (response.IsSuccess == true) {
                var result2 = response.Payload;
                var colsPerRow = GetColsPerRow(result2);
                var colCount = 0;
                if (result2 != null && result2.length > 0) {
                    var content = "<table id='newsTable'>";

                    for (k = 0; k < result2.length; k++) {
                        if (result2[k].length > 0) {
                            if (colCount == 0) {
                                content += "<tr>";
                            }
                            switch (colsPerRow) {
                                case 1:
                                    content += "<td class='SingleColumn'>";
                                    break;
                                case 2:
                                    content += "<td class='TwoColumn'>";
                                    break;
                                default:
                                    content += "<td class='ThreeColumn'>";
                                    break;
                            }
                            content += DisplayNewsHeadlines(result2[k], result2[k][0].sourceId, result2[k][0].sourceName, colsPerRow);
                            content += "</td>";
                            if (colCount == colsPerRow) {
                                content += "</tr>";
                            }
                            colCount++;
                            if (colCount >= colsPerRow) {
                                colCount = 0;
                            }
                        }
                    }
                    if (colCount < colsPerRow) {
                        content += "</tr>";
                    }
                    content += "</table>";
                    newsTable[0].innerHTML = content;
                }
            }
            else {
                ShowErrorMessage(response);
            }
        });
}

function GetNewsColumnHeaderNumber(data) {
    var colCount = 0;
    for (var i = 0; i < data.length; i++) {
        if (data[i].length > 0) {
            colCount++;
        }
    }
    return colCount;
}

function GetColsPerRow(data) {
    /* Set the table width */
    var colsPerRow = 0;
    /* Get the number of news sources with actual data */
    switch (GetNewsColumnHeaderNumber(data)) {
        case 1:
            colsPerRow = 1;
            break;
        case 2:
            colsPerRow = 2;
            break;
        default:
            colsPerRow = 3;
            break;
    }
    return colsPerRow;
}

function SelectSingleNewsSource(sourceId) {
    /* Select all options in a select box */
    var sourceList = $('#searchNewsSourceSelection')[0];
    if (sourceList != null) {
        for (var i = 0; i < sourceList.options.length; i++) {
            if (sourceList.options[i].value == sourceId) {
                sourceList.options[i].selected = true;
            }
            else {
                sourceList.options[i].selected = false;
            }
        }
    }
    Search();
}

// Displays the news headlines for each source. Called from Search()
function DisplayNewsHeadlines(newsFeeds, sourceId, sourceName, colsPerRow) {

    var newsSnippet = "";
    var newsSnippetLength = 50;
    switch (colsPerRow) {
        case 1:
            newsSnippetLength = 190;
            break;
        case 2:
            newsSnippetLength = 90;
            break;
        default:
            newsSnippetLength = 58;
            break;
    }
    var feed = "<table id='" + sourceId + "' style='width:100%'>";
    feed += "<tr><td style='width:100%'><div class='newsSummaryHeader'>";
    feed += "<div class='newsHeader' onclick=SelectSingleNewsSource('" + sourceId + "')>" + sourceName + "</div>";
    feed += "</div></td></tr>";
    if (newsFeeds.length == 0) {
        feed += "<tr>";
        feed += "<td>No results.</td>";
        feed += "</tr>";
    } else {
        for (i = 0; i < newsFeeds.length; i++) {
            if (i % 2 == 0) {
                feed += "<tr class='RowStyle1'>";
            }
            else {
                feed += "<tr class='RowStyle2'>";
            }
            newsSnippet = newsFeeds[i].FullText;
            if (newsSnippet.length > newsSnippetLength) {
                newsSnippet = newsSnippet.substring(0, newsSnippetLength) + "...";
            }
            if (newsFeeds[i].Caption != null && newsFeeds[i].Caption != "") {
                feed += "<td><div ID='" + newsFeeds[i].Id + "'><a href='" + newsFeeds[i].Uri +
                "' onclick=UpdateHitCount('" + newsFeeds[i].Id + "') target='_blank'>" +
                newsFeeds[i].Caption + "</a>" +
                "<br/>" + stripHTML(newsFeeds[i].FullText) +
                "</div></td>";
            }

            feed += "</tr>";
        }
    }
    feed += "</table>";
    return feed;
}

// updates the hit count of a news item
function UpdateHitCount(contentId) {
    var divNews = $("#error")[0];
    contentId = { "id": contentId };
    CallWebService(hitUpdateUrl, contentId, function(result) { });
}

// read all search options and builds the search string
// also validates
function BuildSearchString() {
    //checks
    var startDate = null;
    var endDate = null;
    var searchObject = " ";
    var sources;
    var sortBy;
    var ok = true;
    var temp;
    var sortBy = $("#searchSortBy")[0];
    var sourceList = $('#searchNewsSourceSelection')[0];
    startDate = $("#searchStartDate")[0].value;
    endDate = $("#searchEndDate")[0].value;
    temp = $("#txtSearch")[0].value;

    if (startDate != "" && startDate != null && endDate != null && endDate != "") {
        // todo date validations, difference must be more than 10 days
        var one_day = 1000 * 60 * 60 * 24;
        var dteStartDate = new Date(startDate);
        var dteEndDate = new Date(endDate);
        if (dteStartDate > dteEndDate) {
            alert("The start date cannot be more than the end date. Please correct and search again.");
            // $("#error")[0].innerHTML
            ok = false;
        }
        else {
            if ((Math.ceil((dteEndDate - dteStartDate) / one_day)) > 10) {
                alert("Choose a date range of 10 days or less. Please correct and search again.");
                ok = false;
            }
        }
    }
    if (ok == true) {

        sources = "[";
        var j = 0;
        if (sourceList != null) {
            for (i = 0; i < sourceList.length; i++) {
                if (sourceList[i].selected == true) {
                    if (j == 0) {
                        sources += "" + sourceList[i].value + " ";
                    }
                    else {
                        sources += ", " + sourceList[i].value + "";
                    }
                    j++;
                }
            }
        }
        sources += "]";

        for (i = 0; i < sortBy.length; i++) {
            if (sortBy[i].selected == true) {
                sortBy = sortBy[i].value;
            }
        }

        // Get the selected section (category)
        var section = $(".NewsSection");
        var sectionId = 0;
        for (var i = 0; i < section.length; i++) {
            if (section[i].checked) {
                sectionId = section[i].id.replace("section_", "");
                break;
            }
        }

        /* Hide the search box */
        //var searchBox = $("#advancedNewsSearch");
        //searchBox.hide();

        searchObject = { "startDate": startDate, "endDate": endDate, "searchValue": temp,
            "sortBy": eval(sortBy), "section": sectionId, "newsSources": eval(sources)
        };
    }
    return searchObject;
}

function LoadNewsSections() {
    ClearErrorMessage();
    CallWebService(newsSectionUrl, "", function LoadNewsSectionsResult(serviceResult) {
        var imgLoading = $("#imgLoading")[0];
        var divNews = $(divNews)[0];
        var body = "";
        if (imgLoading != null) {
            imgLoading.style.display = "none";
        }
        var response = JSON.parse(serviceResult.d);
        if (response.IsSuccess) {
            var result = response.Payload;
            var opt;
            var optId;
            for (i = 0; i < result.length; i++) {
                optId = "section_" + result[i].Id;
                body += "<input onclick='Search()' type='radio' class='NewsSection' name='Section.Group' id='" + optId +
                                "' value='" + result[i].Name +
                                ((result[i].Name == "News") ? "' checked='checked'" : "") + "'/>" + result[i].Name + " ";
            }
            $("#newsCategory")[0].innerHTML = body;
        }
        else {
            ShowErrorMessage(response);
        }
    });
}

// called in the Load routine, this function loads news sources into a Select list.
function LoadNewsSourcesInSelectList() {
    var select = $('#searchNewsSourceSelectionDiv')[0];
    var imgLoading = $("#imgLoading")[0];
    var divNews = $(divNews)[0];
    ClearErrorMessage();
    CallWebService(newsSourceUrl, "", function(serviceResult) {
        if (imgLoading != null) {
            imgLoading.style.display = "none";
        }
        var response = JSON.parse(serviceResult.d);
        if (response.IsSuccess) {
            var result = response.Payload;
            var opt = "<select id='searchNewsSourceSelection'  multiple='multiple'>";
            for (i = 0; i < result.length; i++) {
                opt += "<option selected='selected' value='" + result[i].Id + "'>" + result[i].Name + "</option>";
            }
            opt += "</select>";
            select.innerHTML = opt;
            /* Search is called from here, the first time the document loads 
            because this is the longest running method and the source elements 
            will not be ready if called from document ready.
            TODO: find a better way of loading news first time so that it waits until all elements are loaded
            */
            Search();
        }
        else {
            ShowErrorMessage(response);
        }
    });
}

// loads the sort by options
function LoadSortByList() {
    var sortBy = $("#searchSortByDiv")[0];
    sortBy.size = "2"
    var opt = "<select id='searchSortBy'>";

    opt += "<option value='0'>Popularity</option>";
    opt += "<option value='1' selected='selected'>Freshness</option>";
    opt += "</select>";
    sortBy.innerHTML = opt;
}

// Create the body placeholder for a news source
function CreateNewsDiv(source) {
    var text =
                 "<div id='div" + source.Id + "' class='newsSummaryHeadline'>" +
                "<img id='img" + source.Id + "' src='../../Images/loading_animated.gif\' alt='Loading ...' visible='true'/>" +
                "Loading..." +
                "</div>";

    return text;
}

function ClearErrorMessage() {
    $("#error")[0].innerHTML = "";
}
function removeSpaces(string) {
return string.split(' ').join('');
}
